'use strict';

exports.main = async (event, context) => {
  const { username, password } = event;
  const db = uniCloud.database();
  const usersCollection = db.collection('users');

  try {
    // 查找数据库中是否存在用户名
    const userRecord = await usersCollection.where({ username }).get();

    if (userRecord.affectedDocs === 0) {
      return { code: 1, message: "用户名不存在" };
    }

    // 获取用户数据
    const user = userRecord.data[0];

    // 验证密码是否匹配
    if (user.password === password) {
      return { code: 0, message: "登录成功" };
    } else {
      return { code: 2, message: "密码错误" };
    }
  } catch (error) {
    return { code: 500, message: "登录失败，请稍后重试", error };
  }
};
